<!--手机壳商品模块-->

<template>
  <div>
    <TableSearch :query="queryParams" :options="searchOpt" :search="handleSearch"/>
    <div class="container">
      <TableCustom :columns="columns" :tableData="tableData" :total="page.total" :viewFunc="handleView"
                   :delFunc="handleDelete" :editFunc="handleEdit" :refresh="refreshPageEvent"
                   :currentPage="page.index"
                   :changePage="changePage"
                   :page-size="page.size"
                   :delSelection="delSelectionGiftEvent"
                   :pageSizeChange="handleSizeChange"
                   @selection-change="selectChanged"
                   :has-pagination="true">
        <template #toolbarBtn>
          <el-button type="warning" :icon="CirclePlusFilled" @click="visible = true">新增</el-button>
          <el-button type="success" :icon="CirclePlusFilled" @click="excelImportVisible = true">导入</el-button>
          <el-button type="success" :icon="CirclePlusFilled" @click="cdkVisible=true">导出</el-button>
        </template>
        <template #money="{ rows }">
          ￥{{ rows.money }}
        </template>
        <template #thumb="{ rows }">
          <el-image class="table-td-thumb" :src="rows.thumb" :z-index="10" :preview-src-list="[rows.thumb]"
                    preview-teleported>
          </el-image>
        </template>
        <template #state="{ rows }">
          <el-tag :type="rows.state ? 'success' : 'danger'">
            {{ rows.state ? '正常' : '异常' }}
          </el-tag>
        </template>

        <template #operator="{ rows, index }">
          <template v-if="!rows.editing">
            <el-space>

              <el-switch v-model="rows.giftStatus" active-value="启用" inactive-value="禁用"
                         title="切换状态"
                         @change="updateStatusEvent(rows)">
                <template #active-action>
                  <span class="custom-active-action">E</span>
                </template>
                <template #inactive-action>
                  <span class="custom-inactive-action">T</span>
                </template>
              </el-switch>
              <el-button type="primary" size="small" :disabled="rows.status==0" :icon="CirclePlus"
                         @click="generaCdk(rows)"
                         title="生成CDK">
              </el-button>
              <el-button type="success" size="small" :disabled="rows.status==0" :icon="Edit" @click="handleEdit(rows)"
                         title="编辑">
              </el-button>
              <el-popconfirm
                  confirm-button-text="Yes"
                  cancel-button-text="No"
                  :icon="InfoFilled"
                  icon-color="#626AEF"
                  title="确定删除这条数据吗"
                  @confirm="confirmDeleteEvent(rows)"
              >
                <template #reference>
                  <el-button type="danger" size="small" :icon="Delete" title="删除">

                  </el-button>
                </template>

              </el-popconfirm>
            </el-space>
          </template>
          <template v-else>
            <el-button type="success" size="small" :icon="Select" @click="rows.editing = false">
              保存
            </el-button>
            <!--            <el-button type="default" size="small" :icon="CloseBold" @click="handleCancel(rows, index)">-->
            <!--              取消-->
            <!--            </el-button>-->
          </template>
        </template>

      </TableCustom>

    </div>

    <el-dialog :title="isEdit ? '编辑' : '新增'" v-model="visible" width="700px" destroy-on-close
               :close-on-click-modal="false" @close="closeDialog">
      <TableEdit :form-data="rowData" :options="options" :edit="isEdit" :update="updateData" :cancel="cancelOperation">
        <template #thumb="{ rows }">
          <img class="table-td-thumb" :src="rows.thumb"></img>
        </template>
      </TableEdit>
    </el-dialog>
    <el-dialog title="查看详情" v-model="visible1" width="700px" destroy-on-close>
      <TableDetail :data="viewData">
        <template #thumb="{ rows }">
          <el-image :src="rows.thumb"></el-image>
        </template>
      </TableDetail>
    </el-dialog>

    <el-dialog title="从excel导入产品信息" v-model="excelImportVisible" width="700px" destroy-on-close
               :close-on-click-modal="false" @close="closeDialog">
      <TableImport :form-data="rowData" :options="importOption" :edit="isEdit" :update="importFileEvent"
                   :cancel="cancelOperation">
      </TableImport>

    </el-dialog>

  </div>
</template>

<script setup lang="ts" name="phoneManage">
import {getCurrentInstance, onMounted, reactive, ref} from 'vue';
import {ElMessage, ElMessageBox,} from 'element-plus';
import {CirclePlus, CirclePlusFilled, Delete, Edit, InfoFilled, Select} from '@element-plus/icons-vue';
import TableCustom from '@/components/table-custom.vue';
import TableDetail from '@/components/table-detail.vue';
import TableSearch from '@/components/table-search.vue';
import {FormOption, FormOptionList} from '@/types/form-option';
import {exportToXlsx} from "@/utils/exportUtils";
import {PhoneModel} from '@/types/product/phoneModel';
import {GiftManageItem} from "@/types/giftManageItem.ts";
import TableForm from "@/components/table-form.vue";
import TableImport from "@/components/table-import.vue";
import {parseAccountFromFile} from "@/utils/parseAccountFile.ts";
import readXlsxFile from "read-excel-file";

const api = getCurrentInstance()?.appContext.config.globalProperties.$api;

/**
 * 导入steam账号事件
 *
 * **/
const importFileEvent = async (value: object) => {

  console.log(JSON.stringify(value))


  ///
  closeDialog();
  ElMessage.success("正在导入中,请稍后刷新页面查询结果")
  // tableData.value=value
}

const accountFileRef = ref()
const productInfoFilef = ref()
const uploadAccountChanged = async (event, fileList) => {
  if (fileList.length > 1) {
    fileList.splice(0, 1);
  }

  const formData = new FormData();
  formData.append('file', fileList[0].raw);
  formData.append('fileName', fileList[0].raw.fileName);
  const response = await fetch('http://127.0.0.1:5000/upload', {
    method: 'POST',
    body: formData,
    // credentials: 'include' // 如果需要带cookie
  });
  console.log(response)
  // let result = await parseAccountFromFile(event, productInfoFilef.value)
}
/**
 * 导入组件选项
 * **/
let importOption = ref<FormOption>({
  list: [
    {
      type: 'upload', label: '产品文件', ref: accountFileRef,
      changeEvent: uploadAccountChanged,
      fileAccept: ".xlsx",
      prop: 'productFile', required: false, visible: true
    },

  ]
})

// 查询相关
const queryParams = reactive({
  gameName: null,
  appId: null,
  subAppId: null,
  pageSize: 10,
  currentPage: 1,
  gameId: null

});

const page = reactive({
  index: 1,// currentPage
  size: 10, // pageSize
  total: 200, //totalCount
})

const tableData = ref<PhoneModel[]>([]);
const cdkVisible = ref(false)
const searchOpt = ref<FormOptionList[]>([
  {type: 'input', label: '礼物ID：', prop: 'giftId'},
  {type: 'input', label: '礼物名称：', prop: 'giftName'},
  {type: 'select', label: '礼物名称：', prop: 'giftName2'},
])

const excelImportVisible = ref(false)

const handleSearch = () => {
  changePage(1);
};

// 表格相关
let columns = ref([
  {type: 'selection'},
  {type: 'index', label: '序号', width: 55, align: 'center'},
  {prop: 'id', label: 'Id', visible: false},
  {prop: 'isRun', label: '是否读取'},
  {prop: 'number', label: '序号',},
  {prop: 'curBrand', label: '产品', width: 100,},
  {prop: 'link', label: '链接', width: 100,},
  {prop: 'goods_type', label: '宝贝类型', width: 100,},
  {prop: 'main_image_path', label: '主图path', width: 100,},
  {prop: 'product_title', label: '宝贝标题', width: 100,},
  {prop: 'prefix_words', label: '前缀词', width: 100,},
  {prop: 'secondary_keywords', label: '二级关键词', width: 100,},
  {prop: 'random_keywords', label: '随机关键词', width: 100,},
  {prop: 'random_keywords_count', label: '数量', width: 100,},
  {prop: 'shopping_guide_title', label: '导购标题', width: 100,},
  {prop: 'brand', label: '品牌', width: 100,},
  {prop: 'model', label: '型号', width: 100,},
  {prop: 'style', label: '风格', width: 100,},
  {prop: 'fashion_elements', label: '流行元素', width: 100,},
  {prop: 'compatible_phone_models', label: '适用手机机型', width: 100,},
  {prop: 'design', label: '款式', width: 100,},
  {prop: 'function', label: '功能', width: 100,},
  {prop: 'case_material', label: '保护套质地', width: 100,},
  {prop: 'is_biodegradable', label: '是否可降解',},
  {prop: 'is_eco_friendly', label: '是否使用环保材质',},
  {prop: 'procurement_location', label: '采购地',},
  {prop: 'compatible_phone_model_numbers', label: '适用手机型号',},
  {prop: 'color_categories_main', label: '颜色分类（主色必选）',},
  {prop: 'previous_item_image_count', label: '前一项上传几张',},
  {prop: 'color_categories_notes', label: '颜色分类（备注可选）',},
  {prop: 'price', label: '价格',},
  {prop: 'quantity', label: '数量',},
  {prop: 'low_price_sku', label: '低价SKU',},
  {prop: 'merchant_code', label: '商家编码',},
  {prop: 'fixed_price', label: '一口价',},
  {prop: 'purchase_notes', label: '购买须知',},
  {prop: 'reduce_inventory_on_order', label: '拍下减库存',},
  {prop: 'listing_time', label: '上架时间',},
  {prop: 'delivery_time', label: '发货时效',},
  {prop: 'shipping_location', label: '发货地',},
  {prop: 'extraction_method', label: '提取方式',},
  {prop: 'regional_sales_restrictions', label: '区域限售',},
  {prop: 'three_to_four_main_image', label: '3:4主图',},
  {prop: 'product_details', label: '宝贝详情',},
  {prop: 'detail_images_count', label: '一个链接上传几张详情图',},
  {prop: 'insert_prefix_in_first_detail_image', label: '详情首张是否插入前缀图',},
  {prop: 'insert_suffix_in_last_detail_image', label: '详情尾张是否插入后缀图',},
  {prop: 'shop_category', label: '店铺中分类',},
  {prop: 'row', label: '当前行',},
  {prop: 'excelName', label: 'excel名称',},
  {prop: 'rowNumber', label: '行',},
  {prop: 'operator', label: '操作', width: 180, fixed: 'right'},
])

const exportColumn = ref([
  {prop: 'giftId', label: '礼物ID'},
  {prop: 'giftName', label: '礼物名称'},
  {prop: 'cdk', label: 'CDK'},
  {prop: 'batchId', label: '批次ID'},
  {prop: 'giftInsertTime', label: 'CDK生成时间'},
  {prop: 'giftStatus', label: '礼物状态'},
])


const selectRowData = ref([])

const selectChanged = (rows) => {
  selectRowData.value = rows
}

const exportData = async () => {
  let data = selectRowData.value
  if (data.length == 0) {
    data = tableData.value
  }
  let giftIds = []

  data.forEach(item => {
    giftIds.push(item.id)
  })

  if (giftIds.length == 0) {
    ElMessage.info("没有数据可导出")
    return
  }

  let res = await api.post("/api/gift/exportGift", giftIds)
  if (res && res.data) {
    console.log(res.data)
    exportToXlsx(res.data, exportColumn.value, "礼物CDK导出")
  }
}

const updateStatusEvent = (row: any) => {
  console.log(row)
  let params = {
    "id": row.id,
    status: row.giftStatus == '启用' ? 1 : 0
  }
  api.post("/api/gift/updateStatus", params, (res => {
    if (res.code == 1) {
      ElMessage.success("更新成功")
      row.status = params.status;
    } else {
      ElMessage.error("更新失败")
      row.giftStatus = params.status == 1 ? '禁用' : '启用'
    }
  }))
}

const getGiftShopDataList = async (isFresh = false) => {
  api.post("/api/gift/findList", isFresh ? {} : queryParams, (res) => {
    tableData.value = res.data;
    page.total = res.totalPage;
  })
};

/**
 * 页面加载的时候加载数据
 *
 * */
onMounted(() => {
  getGiftShopDataList();
})

const closeCdkPop = () => {
  cdkVisible.value = false
}
const confirmDeleteEvent = (row) => {
  deleteGifts([{id: row.id}])
}
/**
 * 页码改变事件
 * */
const changePage = (val: number) => {
  page.index = val;
  queryParams.currentPage = page.index;
  queryParams.pageSize = page.size;
  getGiftShopDataList();
};

/**
 * 页数大小改变事件
 * */
const handleSizeChange = (val: number) => {
  page.index = 1;
  page.size = val;
  queryParams.currentPage = page.index;
  queryParams.pageSize = page.size;
};

const delSelectionGiftEvent = (val: GiftManageItem[]) => {
  ElMessageBox.confirm(
      '确定删除这些记录吗',
      'Warning',
      {
        confirmButtonText: 'OK',
        cancelButtonText: 'Cancel',
        type: 'warning',
      }
  )
      .then(() => {
        deleteGifts(val.map(e => ({id: e.id})))
      })
      .catch(() => {

      })
}

/**
 * 刷新按钮事件
 *
 * */
const refreshPageEvent = () => {

  getGiftShopDataList(true);
}

// 新增/编辑弹窗相关
let options = ref<FormOption>({
  labelWidth: '500px',
  span: 128,
  list: [
    {type: 'input', prop: 'curBrand', label: '当前产品', defaultValue: '手机壳', disabled: true, required: true,},
    {type: 'input', prop: 'link', label: '链接', required: false,},
    {type: 'input', prop: 'goods_type', label: '类型宝贝', defaultValue: "全新", disabled: true, required: true,},
    {type: 'input', prop: 'main_image_path', label: '主图path', placeholder: "主图片的路径", required: true,},
    {type: 'input', prop: 'product_title', label: '宝贝标题', required: false,},
    {type: 'input', prop: 'prefix_words', label: '前缀词', required: true,},
    {type: 'input', prop: 'secondary_keywords', label: '二级关键词', required: false,},
    {type: 'input', prop: 'random_keywords', label: '随机关键词', required: true, placeholder: "多个用逗号隔开"},
    {type: 'number', prop: 'random_keywords_count', label: '随机关键词数量', required: true,},
    {type: 'input', prop: 'shopping_guide_title', label: '导购标题', required: false, visible: false},
    {type: 'input', prop: 'brand', label: '品牌', required: false, width: '50px'},
    {type: 'input', prop: 'model', label: '型号', required: false,},
    {type: 'input', prop: 'style', label: '风格', required: false, placeholder: "多个用逗号隔开"},
    {type: 'input', prop: 'fashion_elements', label: '流行元素', required: false,},
    {type: 'input', prop: 'compatible_phone_models', label: '适用手机机型', required: false,},
    {type: 'input', prop: 'design', label: '款式', required: false,},
    {type: 'input', prop: 'function', label: '功能', required: false,},
    {type: 'input', prop: 'case_material', label: '保护套质地', required: false,},
    // {type: 'input', prop: 'is_biodegradable', label: '是否可降解', required: true,},
    {
      type: 'switch', activeText: 'Yes', inactiveText: 'No', label: '是否可降解', activeValue: 1,

      inactiveValue: 0, prop: "is_biodegradable", required: false
    },
    {type: 'input', prop: 'is_eco_friendly', label: '环保材质', required: false,},
    {
      type: 'input',
      prop: 'procurement_location',
      label: '采购地',
      disabled: true,
      required: true,
    },
    {
      type: 'input',
      prop: 'compatible_phone_model_numbers',
      label: '适用手机型号',
      required: true,
      placeholder: "多个用逗号隔开"
    },
    {
      type: 'input',
      prop: 'color_categories_main',
      label: '颜色分类图片（路径）',
      required: true,
      placeholder: "输入图片路径"
    },
    {
      type: 'number',
      prop: 'previous_item_image_count',
      label: '前一项上传几张',
      disabled: true,
      required: true,
    },
    {
      type: 'input',
      prop: 'color_categories_notes',
      label: '颜色分类（备注可选）',
      required: false,
      placeholder: "输入一些备注"
    },
    {type: 'input', prop: 'price', label: '价格', required: false,},
    {type: 'input', prop: 'quantity', label: '数量', required: true,},
    {type: 'input', prop: 'low_price_sku', label: '低价SKU', required: false,},
    {type: 'input', prop: 'merchant_code', label: '商家编码', required: false, visible: false},
    {type: 'input', prop: 'fixed_price', label: '一口价', required: false,},
    {type: 'input', prop: 'purchase_notes', label: '购买须知', required: false,},
    {type: 'input', prop: 'reduce_inventory_on_order', label: '拍下减库存', required: false, disabled: true},
    {type: 'input', prop: 'listing_time', label: '上架时间', required: true,},

    {
      type: 'select', prop: 'delivery_time', label: '发货时效', required: true, visible: true,
      opts: [
        {
          label: '24小时内发货', value: 24
        },
        {
          label: '48小时内发货', value: 48
        }

      ],
    },

    {type: 'input', prop: 'shipping_location', label: '发货地', required: true,},
    {type: 'input', prop: 'extraction_method', label: '提取方式', required: true,},
    {type: 'input', prop: 'regional_sales_restrictions', label: '区域限售', required: true, disabled: true},
    {type: 'input', prop: 'three_to_four_main_image', label: '3:4主图', required: false, visible: false},
    {type: 'input', prop: 'product_details', label: '详情图路径', required: true,},
    {
      type: 'number',
      prop: 'detail_images_count',
      label: '一个链接上传几张详情图',
      disabled: true,
      required: true,
    },
    {type: 'input', prop: 'shop_category', label: '店铺中分类', required: false, visible: false},
    // {type: 'number', label: '价格', prop: 'gamePrice', required: true},
    {
      type: 'switch', activeText: 'Yes', inactiveText: 'No', label: '否插入前缀图', activeValue: 1,

      inactiveValue: 0, prop: "insert_prefix_in_first_detail_image", required: false
    },
    {
      type: 'switch', activeText: 'Yes', inactiveText: 'No', label: '是否插入后缀图', activeValue: 1,
      inactiveValue: 0, prop: "insert_suffix_in_last_detail_image", required: false
    },
    // { type: 'upload', label: '头像', prop: 'thumb', required: true },
  ]
})
const visible = ref(false);
const isEdit = ref(false);

const rowData = ref({
  curBrand: '手机壳',
  link: null,
  goods_type: '全新',
  detail_images_count: '5',
  previous_item_image_count: '5',
  product_title: null,
  reduce_inventory_on_order: '否（付款减库存）',
  regional_sales_restrictions: '不设置商品维度区域限售模板',
  procurement_location: '中国内地（大陆）',
  is_eco_friendly: '无环保材料',
  insert_prefix_in_first_detail_image: 1,
  insert_suffix_in_last_detail_image: 1,
});

const editData = ref(false)
const generaCdk = (row: GiftManageItem) => {
  rowData.value = {...row};
  cdkVisible.value = true
  // isEdit.value = true;
  // visible.value = true;
};


const handleEdit = (row: GiftManageItem) => {
  rowData.value = {...row};
  visible.value = true;
  isEdit.value = true;
  editData.value = true;
};

/**
 * 处理点击删除操作事件
 * */
const handleDeleteGift = async (row: GiftManageItem) => {
  let data = {
    id: row.id
  }
  deleteGifts([data]);
}

/**
 *
 * 批量删除操作
 * */
const deleteGifts = async (ids) => {

  api.post("/api/gift/deleteGifts", ids, (res => {
    getGiftShopDataList();
  }))
}

/***
 * 新增/编辑操作
 */
const updateData = async (value) => {
  closeDialog();
  console.log(value)
  tableData.value.push(value)
  if (editData.value == true) {
    editData.value = false
    let res = await api.post("/api/gift/update", value);
    if (res.code == 1) {
      ElMessage.success("更新成功")
    } else {
      ElMessage.error("更新失败")
    }
    getGiftShopDataList();
    return
  }
  // await addGiftGoods([value]);
  // getGiftShopDataList();
};
/**
 *
 * 取消操作
 * **/
const cancelOperation = () => {
  closeDialog();
}

const closeDialog = () => {
  visible.value = false;
  isEdit.value = false;
  excelImportVisible.value = false;
};

// 查看详情弹窗相关
const visible1 = ref(false);
const viewData = ref({
  row: {},
  list: []
});
const handleView = (row: GiftManageItem) => {
  viewData.value.row = {...row}
  viewData.value.list = [
    {
      prop: 'id',
      label: '用户ID',
    },
    {
      prop: 'gameID',
      label: '游戏ID',
    },
    {
      prop: 'gameAppId',
      label: 'appId',
    },
    {
      prop: 'gameSubAppId',
      label: 'SubAppId',
    }, {
      prop: 'gameArea',
      label: '商店区',
    },
    {
      prop: 'gameDesc',
      label: '游戏描述',
    }, {
      prop: 'gameStatus',
      label: '状态',
    },
    {
      prop: 'gamePrice',
      label: '价格',
    },
  ]
  visible1.value = true;
};

// 删除相关
const handleDelete = (row: GiftManageItem) => {
  ElMessage.success('删除成功');
  console.log(row)
}

/**
 * 上传商品
 *
 * **/

const addGiftGoods = async (valueArray: any) => {

  await api.post('/api/gift/addGifts', valueArray);

}


</script>

<style scoped>
.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
</style>
